import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { setupFFmpegHandlers } from './ipc/ffmpeg-handlers';

process.env.DIST = path.join(__dirname, '../dist');
process.env.VITE_PUBLIC = app.isPackaged ? process.env.DIST : path.join(process.env.DIST, '../public');

let win: BrowserWindow | null;

function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 900,
    minHeight: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: true,
    },
    frame: true, // 保留窗口边框
    autoHideMenuBar: true, // 自动隐藏菜单栏
    // titleBarStyle: 'hidden',
    // trafficLightPosition: { x: 15, y: 15 },
    // show: false,
  });

  // 窗口准备好后显示，避免闪烁
  win.once('ready-to-show', () => {
    win?.show();
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    win.webContents.openDevTools();
  } else {
    win.loadFile(path.join(process.env.DIST!, 'index.html'));
  }
}

app.whenReady().then(() => {
  createWindow();

  // 设置 FFmpeg IPC 处理器
  setupFFmpegHandlers();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 监听来自渲染进程的窗口控制请求
ipcMain.handle('window:minimize', () => {
  win?.minimize();
});

ipcMain.handle('window:maximize', () => {
  if (win?.isMaximized()) {
    win.unmaximize();
  } else {
    win?.maximize();
  }
});

ipcMain.handle('window:close', () => {
  win?.close();
});
